/**
 * Copyright 2015 Software innovation and R & D center. All rights reserved.
 * File Name: WxPayController.java
 * Encoding UTF-8
 * Version: 0.0.1
 * History:	2015年3月31日
 */
package cn.apestar.common.pay.wx.web;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import cn.apestar.common.pay.wx.ResponseHandler;
import cn.apestar.common.pay.wx.config.WxPayConfig;
import cn.apestar.common.pay.zfb.entity.NotifyModel;
import cn.apestar.common.utils.DateUtils;


/**
 * 
 * @author: weihuang.peng
 * @version Revision: 0.0.1
 * @Date: 2015年3月31日
 */
@Controller
@RequestMapping(value={"/api/modules/wxpay","/api/modules/wxpay/"})
public class WxPayController {
	

	@SuppressWarnings({ "unused" })
	@RequestMapping("/notify")
	public void notifyUrl(HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		ResponseHandler resHandler = new ResponseHandler(request, response);
		resHandler.setKey(WxPayConfig.APP_KEY);
		if(resHandler.isTenpaySign()) {
			//商户订单号
			String out_trade_no = resHandler.getParameter("out_trade_no");
			//财付通订单号
			String transaction_id = resHandler.getParameter("transaction_id");
			//金额,以分为单位
			String total_fee = resHandler.getParameter("total_fee");
			//如果有使用折扣券，discount有值，total_fee+discount=原请求的total_fee
			String coupon_fee = resHandler.getParameter("coupon_fee");
			//支付结果
			String return_code = resHandler.getParameter("return_code");
			String openid = resHandler.getParameter("openid");
			String time_end = resHandler.getParameter("time_end");
			//判断签名及结果
			if ("SUCCESS".equals(return_code)) {
				SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
				Date date = format.parse(time_end);
				String gmt_payment = DateUtils.formatDate(date, "yyyy-MM-dd HH:mm:ss");
				
				//------------------------------
				//即时到账处理业务开始
				//------------------------------
				System.out.println("you pay for wx success!");
				NotifyModel model = new NotifyModel();
				model.setOut_trade_no(out_trade_no);
				model.setTrade_no(transaction_id);
				model.setPayment_type("2");
				model.setBuyer_email(openid);
				model.setGmt_payment(gmt_payment);
				//------------------------------
				//即时到账处理业务完毕
				//------------------------------
//				alipayService.updateCartInfo(model);
				System.out.println("即时到账支付成功");
				//给财付通系统发送成功信息，财付通系统收到此结果后不再进行后续通知
			} else {
				System.out.println("即时到账支付失败");
			}
			resHandler.sendToCFT("success");
		} else {
			System.out.println("通知签名验证失败");
			resHandler.sendToCFT("fail");
		}
	}
}
